package com.itheima.springbootmybatislilingguo.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.SerializerMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class RabbitMQConfig {

    public static final String DEAD_QUEUE_NAME = "Dead_Queue";
    public static final String DEAD_EXCHANGE_NAME = "Dead_Exchange";

    public static final String QUEUE_NAME = "SpringBoot_Queue";
    public static final String EXCHANGE_NAME = "SpringBoot_Topic_Exchange";

    /**
     * 配置队列
     */
    @Bean("springBootQueue")
    public Queue springBootQueue() {
        return QueueBuilder
                .durable(QUEUE_NAME)
                .withArgument("x-message-ttl", 50000)
                .withArgument("x-dead-letter-exchange", DEAD_EXCHANGE_NAME)
                .withArgument("x-dead-letter-routing-key", "boot.dead")
                .build();
    }

    @Bean("deadQueue")
    public Queue deadQueue() {
        return QueueBuilder
                .durable(DEAD_QUEUE_NAME)
                .build();
    }

    /**
     * 配置交换机
     */
    @Bean("springBootExchange")
    public Exchange springBootExchange() {
        return ExchangeBuilder
                .topicExchange(EXCHANGE_NAME)
                .durable(true)
                .build();
    }

    @Bean("deadExchange")
    public Exchange deadExchange() {
        return ExchangeBuilder
                .topicExchange(DEAD_EXCHANGE_NAME)
                .durable(true)
                .build();
    }

    /**
     * 配置交换机与队列的绑定关系（RoutingKey）
     */
    @Bean
    public Binding bindQueueAndExchange(@Qualifier("springBootExchange") Exchange exchange,
                                        @Qualifier("springBootQueue") Queue queue) {
        return BindingBuilder
                .bind(queue)
                .to(exchange)
                .with("boot.#")
                .noargs();
    }

    @Bean
    public Binding bindDeadQueueAndDeadExchange(@Qualifier("deadExchange") Exchange exchange,
                                                @Qualifier("deadQueue") Queue queue) {
        return BindingBuilder
                .bind(queue)
                .to(exchange)
                .with("boot.dead")
                .noargs();
    }

    /**
     * RabbitTemplate对象
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMandatory(true);
        template.setMessageConverter(new SerializerMessageConverter());
        // producer -> exchange
        template.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack) {
                    System.out.println("exchange has received!");
                } else {
                    System.out.println("exchange has not received!");
                    System.out.println("error cause : " + cause);
                }
            }
        });
        // exchange -> queue
        template.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("error[" + replyCode + "] --> " + exchange + " send '" + new String(message.getBody()) + "' to " + routingKey);
                System.out.println("errorMessage = " + replyText);
            }
        });
        return template;
    }
}
